<template>
  <view class="relative h-screen flex flex-col overflow-hidden">
    <view
      class="flex flex-1 flex-col bg-white transition-transform duration-300 ease-out" :class="[
        {
          'transform-translateX--100%': animateOut,
          'transform-translateX-0': animateIn,
        },
      ]"
    >
      <!-- 固定头部 -->
      <view class="fixed left-0 right-0 z-1000 flex items-center justify-between bg-white px-20rpx"
            :style="headerStyle">
        <view class="flex items-center">
          <image
            class="mr-16rpx h-50rpx w-50rpx" src="https://ceshiweb.picaime.com/static/images/home/diamond.png"
            mode="widthFix"
          />
          <text class="text-36rpx text-[#333] font-bold">
            {{ dangkouName }}
          </text>
          <image
            v-if="hasMultipleMerchants" class="ml-16rpx h-36rpx w-36rpx"
            src="https://ceshiweb.picaime.com/static/images/home/refresh.png" mode="widthFix" @tap="onDangkouNameTap"
          />
        </view>
      </view>

      <!-- 主要内容区域 -->
      <view class="mb-100rpx flex flex-1 flex-col overflow-hidden" :style="{ marginTop: contentMarginTop }">
        <scroll-view class="max-h-[calc(100vh-280rpx)] flex-1" scroll-y>
          <view class="pb-70rpx">
            <!-- 赊欠总额卡片 -->
            <view class="relative m-20rpx overflow-hidden rounded-10rpx bg-[#43cf7c] p-20rpx text-white">
              <image
                class="absolute right--60rpx top--148rpx z-0 w-298rpx transform-rotate--45deg bg-white opacity-10"
                src="https://ceshiweb.picaime.com/static/images/home/bg_top.png" mode="widthFix"
              />
              <image
                class="absolute bottom--130rpx right-100rpx z-0 w-260rpx transform-rotate-45deg bg-white opacity-10"
                src="https://ceshiweb.picaime.com/static/images/home/bg_bottom.png" mode="widthFix"
              />

              <view class="z-1 flex items-center justify-between">
                <view class="flex flex-col">
                  <text class="text-36rpx">
                    赊欠总额
                  </text>
                  <text class="text-46rpx">
                    {{ arrearsTotal }}
                  </text>
                </view>
                <view
                  class="z-1000 rounded-12rpx bg-white px-20rpx py-10rpx text-24rpx text-[#53d387] shadow-[0px_4px_7px_-1px]"
                  @tap="onShareTap"
                >
                  赊欠分享
                </view>
              </view>
              <view class="z-1 mx-20rpx mb-20rpx mr-150rpx mt-20rpx flex justify-between">
                <view class="flex flex-col items-center">
                  <text class="mt-10rpx text-36rpx">
                    {{ monthSales }}
                  </text>
                  <text class="text-24rpx">
                    月销售额/元
                  </text>
                </view>
                <view class="relative flex flex-col items-center">
                  <view class="-top-0rpx absolute z-10 -right-14rpx" @tap="onProfitSettingsTap">
                    <up-icon name="setting" color="rgba(255,255,255,0.8)" size="16"/>
                  </view>
                  <text class="mt-10rpx text-36rpx">
                    {{ monthProfit }}
                  </text>
                  <text class="text-24rpx">
                    日收益/元
                  </text>
                </view>
              </view>
            </view>
            <!-- 功能列表 -->
            <view class="m-20rpx flex flex-wrap rounded-10rpx bg-white py-20rpx">
              <view
                v-for="(item, index) in featureList" :key="index" 
                class="w-1/4 flex flex-col items-center"
                :class="{ 'mb-40rpx': index < 8 }"
                @tap="onFeatureTap(item)"
              >
                <image
                  class="mb-12rpx h-60rpx w-60rpx rounded-50% bg-[rgba(217,217,217,0.32)] p-5rpx"
                  :src="item.icon"
                />
                <text class="text-28rpx text-[#333] font-bold">
                  {{ item.title }}
                </text>
              </view>
            </view>

            <!-- 今日营业概览 -->
            <view class="mx-20rpx my-30rpx rounded-15rpx bg-[#f5f7fa] px-15rpx pb-20rpx pt-15rpx">
              <view class="mb-15rpx mt-15rpx flex items-center">
                <image
                  class="mr-10rpx h-30rpx w-30rpx"
                  src="https://ceshiweb.picaime.com/static/images/home/icon_today_summary.png" mode="widthFix"
                />
                <text class="text-28rpx text-[#333] font-bold tracking-2rpx">
                  今日营业概览
                </text>
              </view>

              <view class="flex flex-wrap justify-between">
                <!-- 营业数据卡片 -->
                <view
                  v-for="item in businessOverviewItems" :key="item.key"
                  class="relative mb-28rpx box-border w-49% rounded-10rpx bg-white px-28rpx pb-10rpx pt-28rpx"
                  @tap="onItemTap(item.title)"
                >
                  <!-- 收益项的设置按钮 -->
                  <view v-if="item.key === 'profit'" class="absolute right-10rpx top-10rpx z-10"
                        @tap.stop="onBusinessProfitSettingsTap">
                    <up-icon name="setting" color="rgba(128,128,128,0.6)" size="20"/>
                  </view>
                  <view class="mb-10rpx flex items-center justify-between">
                    <view class="flex flex-col gap-12rpx">
                      <text class="text-left text-30rpx text-[#808080]">
                        {{ item.label }}
                      </text>
                      <text class="text-36rpx" :class="item.colorClass">
                        {{ item.value }}
                      </text>
                    </view>
                    <image
                      class="h-24rpx w-24rpx" src="https://ceshiweb.picaime.com/static/images/home/arrow_right.png"
                      mode="widthFix"
                    />
                  </view>
                </view>
                <!-- 销量统计卡片 -->
                <view
                  class="box-border w-100% rounded-10rpx bg-white px-28rpx pb-20rpx pt-28rpx"
                  @tap="onItemTap('销量')"
                >
                  <view class="flex items-center justify-between">
                    <view v-for="item in salesStatistics" :key="item.key" class="flex flex-col items-center">
                      <text class="mb-8rpx text-36rpx text-[#27ae60] font-bold">
                        {{ item.value }}
                      </text>
                      <text class="text-24rpx text-[#808080]">
                        {{ item.label }}
                      </text>
                    </view>
                  </view>
                </view>
              </view>
            </view>

            <!-- 七日销售趋势 -->
            <view class="my-30rpx rounded-15rpx pb-20rpx pt-15rpx">
              <view class="flex items-center justify-between pl-5 pr-5">
                <text class="text-28rpx text-[#333] font-bold tracking-2rpx">
                  七日销售趋势
                </text>
                <view class="flex items-center">
                  <view class="mr-20rpx flex items-center">
                    <text class="text-30rpx text-[#1890ff]">
                      ●
                    </text>
                    <text class="ml-5rpx text-30rpx text-[#666]">
                      总销量
                    </text>
                  </view>
                  <view class="flex items-center">
                    <text class="text-30rpx text-[#4CAF50]">
                      ●
                    </text>
                    <text class="ml-5rpx text-30rpx text-[#666]">
                      总金额
                    </text>
                  </view>
                </view>
              </view>
              <qiun-data-charts type="mix" :opts="chartOpts" :chart-data="chartData"/>
            </view>
          </view>
        </scroll-view>
      </view>

      <custom-tabbar @navigate="handleNavigate"/>
    </view>

    <!-- 档口选择弹窗 -->
    <AccountSelector
      :show="showAccountSelector" :accounts="accountOptions" @confirm="handleAccountConfirm"
      @cancel="handleAccountCancel"
    />

    <!-- 日收益设置弹窗 -->
    <up-popup :show="showProfitSettings" mode="bottom" round="20" :custom-style="{ height: profitPopupHeight }"
              @close="showProfitSettings = false">
      <view class="p-30rpx h-full flex flex-col">
        <view class="mb-20rpx flex items-center justify-between flex-shrink-0">
          <view class="flex items-center">
            <text class="text-32rpx font-bold">
              日收益设置
            </text>
            <text class="ml-20rpx text-24rpx text-gray-500">
              选择计入日收益的项目
            </text>
          </view>
          <up-icon name="close" size="24" @click="showProfitSettings = false"/>
        </view>

        <view class="mb-20rpx overflow-y-auto">
          <view class="flex flex-col gap-20rpx">
            <view
              v-for="(item, index) in profitItems"
              :key="index"
              class="relative flex flex-row items-center justify-between rounded-15rpx border-2 px-30rpx py-25rpx transition-all"
              :class="[
                item.checked
                  ? 'border-[#43cf7c] bg-[#43cf7c]'
                  : 'border-[#f5f7fa] bg-[#f5f7fa]'
              ]"
              @tap="toggleProfitItem(index)"
            >
              <view class="flex flex-row items-center gap-20rpx">
                <text class="text-28rpx font-bold" :class="item.checked ? 'text-white' : 'text-[#333]'">
                  {{ item.name }}
                </text>
                <text class="text-24rpx" :class="item.checked ? 'text-white' : 'text-gray-500'">
                  {{ item.value }}元
                </text>
              </view>

              <!-- 选中对号 -->
              <view class="flex-shrink-0 h-40rpx w-40rpx flex items-center justify-center">
                <up-icon v-if="item.checked" name="checkmark" color="white" size="20"/>
              </view>
            </view>
          </view>
        </view>

        <view class="flex items-center justify-between rounded-10rpx bg-gray-50 px-20rpx py-20rpx flex-shrink-0">
          <text class="text-30rpx font-bold">
            当前日收益：
          </text>
          <text class="text-30rpx text-green-500 font-bold">
            {{ monthProfit }}元
          </text>
        </view>
      </view>
    </up-popup>

    <!-- 今日营业概览收益设置弹窗 -->
    <up-popup :show="showBusinessProfitSettings" mode="bottom" round="20"
              :custom-style="{ height: businessProfitPopupHeight }"
              @close="showBusinessProfitSettings = false">
      <view class="p-30rpx h-full flex flex-col">
        <view class="mb-20rpx flex items-center justify-between flex-shrink-0">
          <view class="flex items-center">
            <text class="text-32rpx font-bold">
              收益设置
            </text>
            <text class="ml-20rpx text-24rpx text-gray-500">
              选择计入收益的项目
            </text>
          </view>
          <up-icon name="close" size="24" @click="showBusinessProfitSettings = false"/>
        </view>

        <view class="mb-20rpx flex-1 overflow-y-auto">
          <view class="flex flex-col gap-20rpx">
            <view
              v-for="(item, index) in businessProfitItems"
              :key="index"
              class="relative flex flex-row items-center justify-between rounded-15rpx border-2 px-30rpx py-25rpx transition-all"
              :class="[
                item.checked
                  ? 'border-[#43cf7c] bg-[#43cf7c]'
                  : 'border-[#f5f7fa] bg-[#f5f7fa]'
              ]"
              @tap="toggleBusinessProfitItem(index)"
            >
              <view class="flex flex-row items-center gap-20rpx">
                <text class="text-28rpx font-bold" :class="item.checked ? 'text-white' : 'text-[#333]'">
                  {{ item.name }}
                </text>
                <text class="text-24rpx" :class="item.checked ? 'text-white' : 'text-gray-500'">
                  {{ item.value }}元
                </text>
              </view>

              <!-- 选中对号 -->
              <view class="flex-shrink-0 h-40rpx w-40rpx flex items-center justify-center">
                <up-icon v-if="item.checked" name="checkmark" color="white" size="20"/>
              </view>
            </view>
          </view>
        </view>

        <view class="flex items-center justify-between rounded-10rpx bg-gray-50 px-20rpx py-20rpx flex-shrink-0">
          <text class="text-30rpx font-bold">
            当前收益：
          </text>
          <text class="text-30rpx text-green-500 font-bold">
            {{ calculateBusinessProfitValue() }}元
          </text>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import type {AccountOption, LoginRes} from '@/api/user/types';
import {onLoad, onShow} from '@dcloudio/uni-app';
import {computed, reactive, ref} from 'vue';
import {getArrearsTotal} from '@/api/member/index';
import {getDailyData, getDayReport, getMonthlyReport, getYingshouReport} from '@/api/report';
import AccountSelector from '@/components/AccountSelector/index.vue';
import customTabbar from '@/components/custom-tabbar/custom-tabbar.vue';
import qiunDataCharts from '@/components/eahcart/qiun-data-charts/qiun-data-charts.vue';
import usePermission from '@/hooks/use-permission';
import {useUserStore} from '@/store';
import AccountCacheManager from '@/utils/accountCache';
import {clearToken} from '@/utils/auth';

// 功能项类型定义
interface FeatureItem {
  title: string;
  icon: string;
  url?: string;
}

// 营业概览项类型定义
interface BusinessOverviewItem {
  key: string;
  title: string;
  label: string;
  value: string;
  colorClass: string;
}

// 销量统计项类型定义
interface SalesStatItem {
  key: string;
  label: string;
  value: string;
}

const userStore = useUserStore();

// 获取胶囊按钮的位置信息
const menuButtonInfo = ref<UniApp.GetMenuButtonBoundingClientRectRes | null>(null);
const statusBarHeight = ref(0);
const windowHeight = ref(0); // 屏幕高度
const windowWidth = ref(0); // 屏幕宽度

// 页面状态
const animateOut = ref(false);
const animateIn = ref(true);
const dangkouName = ref('');
const arrearsTotal = ref('0');
const monthSales = ref('0');
const monthProfit = ref('0');

// 日收益设置相关状态
const showProfitSettings = ref(false);
const profitItems = ref([
  {name: '力资', value: 0, checked: true},
  {name: '开票', value: 0, checked: true},
  {name: '押金', value: 0, checked: true},
  {name: '收费名字', value: 0, checked: true},
]);

// 今日营业概览收益设置相关状态
const showBusinessProfitSettings = ref(false);
const businessProfitItems = ref([
  {name: '力资', value: 0, checked: true},
  {name: '开票', value: 0, checked: true},
  {name: '押金', value: 0, checked: true},
  {name: '收费名字', value: 0, checked: true},
]);

// 图表数据
const chartData = ref<any>({
  categories: ['06-05', '06-06', '06-07', '06-08', '06-09', '06-10', '06-11'],
  series: [],
});

// 图表配置
const chartOpts = {
  padding: [15, 15, 0, 15],
  enableScroll: false,
  legend: {
    show: false,
  },
  xAxis: {disableGrid: true},
  yAxis: {disabled: true},
  extra: {
    mix: {
      column: {width: 20},
    },
  },
};

// 账户选择器相关状态
const showAccountSelector = ref(false);
const accountOptions = ref<AccountOption[]>([]);

// 计算导航栏样式
const headerStyle = computed(() => {
  if (!menuButtonInfo.value) {
    return {
      top: '80rpx',
      height: '80rpx',
    };
  }

  const menuButtonHeight = menuButtonInfo.value.height;
  const menuButtonTop = menuButtonInfo.value.top;
  const statusBar = statusBarHeight.value;

  const navigationBarHeight = menuButtonHeight + (menuButtonTop - statusBar) * 2;

  return {
    top: `${statusBar}px`,
    height: `${navigationBarHeight}px`,
  };
});

// 计算内容区域的上边距
const contentMarginTop = computed(() => {
  if (!menuButtonInfo.value) {
    return '150rpx';
  }

  const statusBar = statusBarHeight.value;
  const menuButtonHeight = menuButtonInfo.value.height;
  const menuButtonTop = menuButtonInfo.value.top;
  const navigationBarHeight = menuButtonHeight + (menuButtonTop - statusBar) * 2;
  const totalHeight = statusBar + navigationBarHeight;

  return `${totalHeight}px`;
});

// 计算是否有多个档口
const hasMultipleMerchants = computed(() => {
  try {
    const cacheData = uni.getStorageSync('multi_account_cache');
    if (!cacheData) return false;

    const parsedData = typeof cacheData === 'string' ? JSON.parse(cacheData) : cacheData;
    return parsedData?.accounts && Array.isArray(parsedData.accounts) && parsedData.accounts.length > 1;
  } catch (error) {
    console.error('获取多账户缓存失败:', error);
    return false;
  }
});

// 动态计算日收益设置弹窗高度
const profitPopupHeight = computed(() => {
  if (!windowHeight.value || !windowWidth.value) return '45vh';

  // rpx 转 px 的系数
  const rpxToPx = windowWidth.value / 750;

  // 每个项目: py-25rpx * 2 + 文字高度 30rpx + gap 20rpx = 100rpx
  // 标题: mb-20rpx + 文字 40rpx = 60rpx
  // 底部: py-20rpx * 2 + 文字 30rpx + mb-20rpx = 90rpx
  // 内边距: p-30rpx * 2 = 60rpx
  const itemCount = profitItems.value.length;
  const estimatedHeightRpx = itemCount * 100 + 60 + 90 + 60;
  const estimatedHeight = estimatedHeightRpx * rpxToPx + 10; // 增加10px额外空间

  // 最小 250px，最大 70% 屏幕高度
  const minHeight = 250;
  const maxHeight = windowHeight.value * 0.7;
  const finalHeight = Math.min(Math.max(estimatedHeight, minHeight), maxHeight);

  return `${finalHeight}px`;
});

// 动态计算今日营业概览收益设置弹窗高度
const businessProfitPopupHeight = computed(() => {
  if (!windowHeight.value || !windowWidth.value) return '50vh';

  // rpx 转 px 的系数
  const rpxToPx = windowWidth.value / 750;

  // 每个项目: py-25rpx * 2 + 文字高度 30rpx + gap 20rpx = 100rpx
  // 标题: mb-20rpx + 文字 40rpx = 60rpx
  // 底部: py-20rpx * 2 + 文字 30rpx + mb-20rpx = 90rpx
  // 内边距: p-30rpx * 2 = 60rpx
  const itemCount = businessProfitItems.value.length;
  const estimatedHeightRpx = itemCount * 100 + 60 + 90 + 60;
  const estimatedHeight = estimatedHeightRpx * rpxToPx + 10; // 增加10px额外空间

  // 最小 250px，最大 70% 屏幕高度
  const minHeight = 250;
  const maxHeight = windowHeight.value * 0.7;
  const finalHeight = Math.min(Math.max(estimatedHeight, minHeight), maxHeight);

  return `${finalHeight}px`;
});
// 功能列表
const featureList: FeatureItem[] = [
  {
    title: '赊欠录入',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_arrears.png',
    url: '/pages/credit/credit'
  },
  {
    title: '收入支出',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_income_expense.png',
    url: '/pages/income/income'
  },
  {
    title: '快捷还款',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_quick_repay.png',
    url: '/pages/repay/repay'
  },
  {
    title: '货主批次',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_owner_batch.png',
    url: '/pages/tab/batch/batch'
  },
  {
    title: '订单管理',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_order_manage.png',
    url: '/pages/order/order'
  },
  {
    title: '买家管理',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_buyer_manage.png',
    url: '/pages/tab/list/buyer'
  },
  {
    title: '货品管理',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_goods_manage.png',
    url: '/pages/common/goods/index'
  },
  {
    title: '库存管理',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_stock_manage.png',
    url: '/pages/tab/stock/stock'
  },
  {title: '标签打印', icon: 'https://ceshiweb.picaime.com/static/images/home/icon_label_print.png'},
  {
    title: '报表中心',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_report_center.png',
    url: '/pages/report/index'
  },
  {
    title: '赊欠详情',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_bulk_order.png',
    url: '/pages/tab/list/debt'
  },
  {
    title: '批量下单',
    icon: 'https://ceshiweb.picaime.com/static/images/home/icon_bulk_order1.png',
    url: '/pages/import/buyer-import'
  },
];

// 日报告数据
const dayReport = reactive({
  totalOrders: 0,
  totalRevenue: '0',
  totalExpense: '0',
  buyerCount: 0,
  buyerArrears: '0',
  historyCount: 0,
  historyRepayment: '0',
  otherIncome: '0',
  totalCollection: '0',
  profit: '0',
  salesVolume: '0',
  salesCount: '0',
  salesWeight: '0',
  soldBatches: '0',
  soldGoods: '0',
});

// 营业概览数据
const businessOverviewItems = computed<BusinessOverviewItem[]>(() => [
  {
    key: 'revenue',
    title: '总营收',
    label: `总营收（${dayReport.totalOrders}单）`,
    value: dayReport.totalRevenue,
    colorClass: 'text-[#1b98f5]'
  },
  {key: 'expense', title: '总支出', label: '总支出', value: dayReport.totalExpense, colorClass: 'text-[#e74c3c]'},
  {
    key: 'arrears',
    title: '买家赊欠',
    label: `买家赊欠（${dayReport.buyerCount}人）`,
    value: dayReport.buyerArrears,
    colorClass: 'text-[#f39c12]'
  },
  {
    key: 'repayment',
    title: '历史还款',
    label: `历史还款（${dayReport.historyCount}人）`,
    value: dayReport.historyRepayment,
    colorClass: 'text-[#1b98f5]'
  },
  {
    key: 'otherIncome',
    title: '其他收入',
    label: '其他收入',
    value: dayReport.otherIncome,
    colorClass: 'text-[#27ae60]'
  },
  {key: 'collection', title: '总收款', label: '总收款', value: dayReport.totalCollection, colorClass: 'text-[#1b98f5]'},
  {key: 'profit', title: '收益', label: '收益', value: dayReport.profit, colorClass: 'text-[#27ae60]'},
]);

// 销量统计数据
const salesStatistics = computed<SalesStatItem[]>(() => [
  {key: 'count', label: '销售数量', value: dayReport.salesCount},
  {key: 'weight', label: '销售重量', value: dayReport.salesWeight},
  {key: 'batches', label: '已售批次', value: `${dayReport.soldBatches}`},
  {key: 'goods', label: '已售货品', value: `${dayReport.soldGoods}`},
]);

// 生成日期范围（今天往前推6天，共7天）
const generateDateRange = (): string[] => {
  const today = new Date();
  const endDate = today.toISOString().split('T')[0];
  const startDate = new Date(today);
  startDate.setDate(today.getDate() - 6);
  return [startDate.toISOString().split('T')[0], endDate];
};

// 获取七日销售趋势数据
const fetchDailyData = async (): Promise<void> => {
  try {
    const dateRange = generateDateRange();
    const res = await getDailyData({date: dateRange});

    if (res.code === 200 && res.data) {
      const {X_data, Y_today_data, Y_all_data} = res.data;
      chartData.value = {
        categories: X_data,
        series: [
          {
            name: '总金额',
            linearColor: [[0, '#1890FF'], [0.25, '#00B5FF'], [0.5, '#00D1ED'], [0.75, '#00E6BB'], [1, '#90F489']],
            setShadow: [3, 8, 10, '#1890FF'],
            data: Y_today_data,
            type: 'line',
            style: 'curve',
            color: '#1890ff',
            disableLegend: true,
          },
          {
            name: '总销量',
            data: Y_all_data.map((value: number) => ({value, color: '#91cc75'})),
            type: 'column',
          },
        ],
      };
    }
  } catch (error) {
    console.error('获取七日销售趋势失败:', error);
  }
};

// 获取赊欠总额数据
const fetchArrearsTotal = async (): Promise<void> => {
  try {
    const res = await getArrearsTotal();
    if (res.code === 200 && res.data) {
      // 从响应中获取 total_price 作为赊欠总额
      arrearsTotal.value = res.data.total_price?.toString() || '0';
    }
  } catch (error) {
    console.error('获取赊欠总额失败:', error);
  }
};

// 获取月销售额和日收益数据
const fetchMonthlySales = async (): Promise<void> => {
  try {
    const res = await getMonthlyReport({date: 'today'});
    if (res.code === 200 && res.data && res.data.name) {
      // 计算所有 name 项下 smallCards 中 number 的总和
      let totalSales = 0;

      res.data.name.forEach((nameItem: any) => {
        if (nameItem.smallCards && Array.isArray(nameItem.smallCards)) {
          nameItem.smallCards.forEach((card: any) => {
            const cardNumber = typeof card.number === 'string' ? Number.parseFloat(card.number) : card.number;
            if (!Number.isNaN(cardNumber)) {
              totalSales += cardNumber;
            }
          });
        }
      });

      monthSales.value = totalSales.toString();

      // 提取日收益相关数据（力资、开票、押金、收费名字）
      res.data.name.forEach((nameItem: any) => {
        if (nameItem.smallCards && Array.isArray(nameItem.smallCards)) {
          nameItem.smallCards.forEach((card: any) => {
            const itemIndex = profitItems.value.findIndex((item: any) => item.name === card.title);
            if (itemIndex !== -1) {
              const cardNumber = typeof card.number === 'string' ? Number.parseFloat(card.number) : card.number;
              profitItems.value[itemIndex].value = Number.isNaN(cardNumber) ? 0 : cardNumber;
            }
          });
        }
      });

      // 从本地存储恢复勾选状态
      loadProfitItemsFromStorage();

      // 计算日收益
      calculateDailyProfit();
    }
  } catch (error) {
    console.error('获取月销售额失败:', error);
  }
};
// 计算日收益
const calculateDailyProfit = (): void => {
  let total = 0;
  profitItems.value.forEach((item: any) => {
    if (item.checked) {
      total += item.value;
    }
  });
  monthProfit.value = total.toString();
};

// 计算今日营业概览收益
const calculateBusinessProfit = (): void => {
  // 这个函数用于触发收益重新计算，实际计算在 calculateBusinessProfitValue 中
  // 这里可以添加其他需要在收益更新时执行的逻辑
};

// 计算今日营业概览收益值
const calculateBusinessProfitValue = (): number => {
  let total = 0;
  businessProfitItems.value.forEach((item: any) => {
    if (item.checked) {
      total += item.value;
    }
  });
  return total;
};

// 获取营收数据（用于销量统计）
const fetchYingshouData = async (): Promise<void> => {
  try {
    const res = await getYingshouReport();
    if (res.code === 200 && res.data && res.data.yingshou) {
      // 查找category_name为"总计"的数据行
      const totalRow = res.data.yingshou.find((item: any) => item.category_name === '总计');

      if (totalRow) {
        // 更新销量统计数据
        Object.assign(dayReport, {
          // 已售批次：从pici_name获取，如果为空则使用默认值
          soldBatches: totalRow.pici_name || '0',
          // 销售数量：从sale_num获取
          salesCount: totalRow.sale_num?.toString() || '0',
          // 销售重量：从sale_num获取（根据接口说明，销售重量也使用sale_num）
          salesWeight: totalRow.sale_num?.toString() || '0',
          // 已售货品：从goods_name获取，如果为空则使用默认值
          soldGoods: totalRow.goods_name || '0',
        });
      }
    }
  } catch (error) {
    console.error('获取营收数据失败:', error);
  }
};

// 获取日报告数据
const fetchDayReport = async (): Promise<void> => {
  try {
    const res = await getDayReport({date: 'today'});
    if (res.code === 200 && res.data) {
      const {statistics, total_yingshou, statistics_income} = res.data;

      // 统计项映射
      const statisticsMap = new Map(statistics.map((item: any) => [item.title, item.number || '0']));

      // 提取今日营业概览收益相关数据（从 statistics_income.income_type）
      if (statistics_income && statistics_income.income_type) {
        statistics_income.income_type.forEach((item: any) => {
          const itemIndex = businessProfitItems.value.findIndex((profitItem: any) => profitItem.name === item.name);
          if (itemIndex !== -1) {
            businessProfitItems.value[itemIndex].value = item.value || 0;
          }
        });
      }

      // 从本地存储恢复勾选状态
      loadBusinessProfitItemsFromStorage();

      // 计算今日营业概览收益
      calculateBusinessProfit();

      // 更新日报告数据
      Object.assign(dayReport, {
        totalRevenue: statisticsMap.get('货款总额') || '0',
        totalExpense: statisticsMap.get('支出') || '0',
        buyerArrears: statisticsMap.get('赊欠') || '0',
        historyRepayment: statisticsMap.get('还款') || '0',
        // 其他收入：从 statistics 数组中获取 "其他收入" 项的 number 值
        otherIncome: statisticsMap.get('其他收入') || '0',
        // 总收款：直接使用 total_yingshou 字段
        totalCollection: total_yingshou || '0',
        // 收益：使用计算出的收益值
        profit: calculateBusinessProfitValue().toString(),
        salesVolume: statisticsMap.get('销量') || '0',
        // 注意：销售数量、销售重量、已售批次、已售货品将由fetchYingshouData更新
        salesCount: statisticsMap.get('销售数量') || '0',
        salesWeight: statisticsMap.get('销售重量') || '0',
        soldBatches: statisticsMap.get('已售批次') || '0',
        soldGoods: statisticsMap.get('已售货品') || '0',
        totalOrders: total_yingshou ? Number.parseInt(total_yingshou) : 0,
        buyerCount: 0,
        historyCount: 0,
      });
    }
  } catch (error) {
    console.error('获取日报告失败:', error);
  }
};

// 获取店铺名称
const getDangkouName = (): void => {
  try {
    dangkouName.value = userStore.dangkou_name || '云批宝';
  } catch (error) {
    console.error('获取店铺名称失败:', error);
    dangkouName.value = '云批宝';
  }
};

// 点击档口名称
const onDangkouNameTap = (): void => {
  if (!hasMultipleMerchants.value) return;

  try {
    const cacheData = uni.getStorageSync('multi_account_cache');
    const parsedData = typeof cacheData === 'string' ? JSON.parse(cacheData) : cacheData;
    const accounts = parsedData?.accounts;

    if (accounts && accounts.length > 0) {
      accountOptions.value = accounts;
      showAccountSelector.value = true;
    }
  } catch (error) {
    console.error('获取账户缓存失败:', error);
  }
};

// 处理账户选择确认
const handleAccountConfirm = async (selectedAccount: AccountOption): Promise<void> => {
  showAccountSelector.value = false;

  try {
    uni.showLoading({title: '切换档口中...'});

    // 清空登录缓存但保留 multi_account_cache
    clearToken();
    userStore.resetInfo();

    // 从缓存获取密码信息
    const cacheInfo = AccountCacheManager.getCacheInfo();
    if (!cacheInfo?.password) {
      uni.hideLoading();
      uni.showToast({title: '缓存信息不完整，请重新登录', icon: 'none'});
      return;
    }

    // 使用选中的账户信息执行登录操作
    const res = await userStore.login({
      account: selectedAccount.mobile,
      password: cacheInfo.password,
      id: selectedAccount.id,
    }) as LoginRes;

    uni.hideLoading();

    if (res.code === 200) {
      dangkouName.value = selectedAccount.dangkou_name || selectedAccount.name;
      uni.showToast({title: '切换成功', icon: 'success'});

      // 重新获取数据
      await Promise.all([fetchDayReport(), fetchDailyData(), fetchArrearsTotal(), fetchMonthlySales(), fetchYingshouData()]);
    } else {
      uni.showToast({title: res.msg || '切换失败', icon: 'none'});
    }
  } catch (error) {
    uni.hideLoading();
    console.error('切换档口失败:', error);
    uni.showToast({title: '切换失败', icon: 'none'});
  }
};

// 处理账户选择取消
const handleAccountCancel = (): void => {
  showAccountSelector.value = false;
};

// 功能项点击事件
const onFeatureTap = (item: FeatureItem): void => {
  if (item.url) {
    uni.navigateTo({url: item.url});
  }
};

// 营业概览项点击事件
const onItemTap = (type: string): void => {
  console.log('点击了:', type);
};

// 点击赊欠分享按钮
const onShareTap = (): void => {
  uni.navigateTo({url: '/pages/tab/list/debt'});
};

// 点击日收益设置按钮
const onProfitSettingsTap = (): void => {
  showProfitSettings.value = true;
};

// 日收益项目选择变化
const onProfitItemChange = (): void => {
  calculateDailyProfit();
};

// 切换日收益项目
const toggleProfitItem = (index: number): void => {
  profitItems.value[index].checked = !profitItems.value[index].checked;
  calculateDailyProfit();
  // 保存到本地存储
  saveProfitItemsToStorage();
};

// 保存日收益项目到本地存储
const saveProfitItemsToStorage = (): void => {
  try {
    const checkedState = profitItems.value.map(item => ({
      name: item.name,
      checked: item.checked,
    }));
    uni.setStorageSync('profit_items_checked', JSON.stringify(checkedState));
  } catch (error) {
    console.error('保存日收益项目失败:', error);
  }
};

// 从本地存储恢复日收益项目
const loadProfitItemsFromStorage = (): void => {
  try {
    const savedState = uni.getStorageSync('profit_items_checked');
    if (savedState) {
      const checkedState = JSON.parse(savedState);
      profitItems.value.forEach((item) => {
        const savedItem = checkedState.find((s: any) => s.name === item.name);
        if (savedItem) {
          item.checked = savedItem.checked;
        }
      });
      calculateDailyProfit();
    }
  } catch (error) {
    console.error('加载日收益项目失败:', error);
  }
};

// 点击今日营业概览收益设置按钮
const onBusinessProfitSettingsTap = (): void => {
  showBusinessProfitSettings.value = true;
};

// 今日营业概览收益项目选择变化
const onBusinessProfitItemChange = (): void => {
  // 重新计算收益并更新dayReport中的profit值
  const newProfitValue = calculateBusinessProfitValue();
  dayReport.profit = newProfitValue.toString();
};

// 切换今日营业概览收益项目
const toggleBusinessProfitItem = (index: number): void => {
  businessProfitItems.value[index].checked = !businessProfitItems.value[index].checked;
  const newProfitValue = calculateBusinessProfitValue();
  dayReport.profit = newProfitValue.toString();
  // 保存到本地存储
  saveBusinessProfitItemsToStorage();
};

// 保存今日营业概览收益项目到本地存储
const saveBusinessProfitItemsToStorage = (): void => {
  try {
    const checkedState = businessProfitItems.value.map(item => ({
      name: item.name,
      checked: item.checked,
    }));
    uni.setStorageSync('business_profit_items_checked', JSON.stringify(checkedState));
  } catch (error) {
    console.error('保存今日营业概览收益项目失败:', error);
  }
};

// 从本地存储恢复今日营业概览收益项目
const loadBusinessProfitItemsFromStorage = (): void => {
  try {
    const savedState = uni.getStorageSync('business_profit_items_checked');
    if (savedState) {
      const checkedState = JSON.parse(savedState);
      businessProfitItems.value.forEach((item) => {
        const savedItem = checkedState.find((s: any) => s.name === item.name);
        if (savedItem) {
          item.checked = savedItem.checked;
        }
      });
      const newProfitValue = calculateBusinessProfitValue();
      dayReport.profit = newProfitValue.toString();
    }
  } catch (error) {
    console.error('加载今日营业概览收益项目失败:', error);
  }
};

// 处理导航事件
const handleNavigate = ({type, url}: { type: string; url: string }): void => {
  if (type === 'navigateTo') {
    animateOut.value = true;
    setTimeout(() => {
      animateOut.value = false;
      uni.navigateTo({url});
    }, 300);
  } else if (type === 'switchTab') {
    uni.switchTab({url});
  }
};

// 页面显示时的处理
onShow(() => {
  usePermission();

  // 页面进入动画
  animateIn.value = true;
  setTimeout(() => {
    animateIn.value = false;
  }, 300);

  // 获取数据
  Promise.all([fetchDayReport(), fetchDailyData(), fetchArrearsTotal(), fetchMonthlySales(), fetchYingshouData()]);
  getDangkouName();
});

// 页面首次加载时的处理
onLoad(() => {
  usePermission();
  getDangkouName();

  // #ifdef MP-WEIXIN
  // 获取胶囊按钮位置信息
  menuButtonInfo.value = uni.getMenuButtonBoundingClientRect();
  // 获取系统信息中的状态栏高度
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;
  windowHeight.value = systemInfo.windowHeight || 0;
  windowWidth.value = systemInfo.windowWidth || 0;
  // #endif

  // #ifndef MP-WEIXIN
  // 非微信小程序也获取屏幕尺寸
  const systemInfo = uni.getSystemInfoSync();
  windowHeight.value = systemInfo.windowHeight || 0;
  windowWidth.value = systemInfo.windowWidth || 0;
  // #endif
});
</script>
